package 算法.leetcode.stack;

import org.junit.Test;

import java.util.Stack;

/**
 * 有效括号
 *
 * @author lchenglong
 * @date 2021/1/5
 */
public class IsValid {
    @Test
    public void test() {
        System.out.println(isValid("()[{]"));
    }
    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<Character>();
        for (int i=0;i<s.length();i++) {
            Character cur = s.charAt(i);

            Character top = null;
            if (!stack.empty()) {
                top = stack.peek();
            }
            if (equals(cur,top)){
                stack.pop();
            } else {
                stack.push(s.charAt(i));
            }
        }
        if (stack.empty()){
            return true;
        } else {
            return false;
        }
    }

    public boolean equals(Character cur,Character top) {
        if (top == null) return false;
        // '('，')'，'{'，'}'，'['，']'
        Character cur2 = null;
        switch (cur) {
            case ')' :
                cur2 = '(';
                break;
            case '}':
                cur2 = '{';
                break;
            case ']':
                cur2 = '[';
                break;
            default:
                cur2 = '0';
        }
       return cur2.equals(top);
    }
}
